package com.pricy.me;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Currency;
import java.util.Locale;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.pricy.me.model.User;
import com.pricy.me.utils.EmailValidator;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class InscriptionDialog extends Dialog{

	private Context context;
	private ProgressDialog mProgress;
	
	public InscriptionDialog(final Context context) {
		super(context);
		this.context = context;
		mProgress		= new ProgressDialog(context);
		
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.login_email);
		this.setCanceledOnTouchOutside(false);
		final EditText firstname = (EditText) findViewById(R.id.login_firstname);
		final EditText lastname = (EditText) findViewById(R.id.login_lastname);
		final EditText email = (EditText) findViewById(R.id.login_email);
		final EditText pwd = (EditText) findViewById(R.id.login_pwd);
		final EditText pwd2 = (EditText) findViewById(R.id.login_pwd2);
		Button loginBtn = (Button) findViewById(R.id.login_btn);
		
		loginBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				boolean flag = true;
				
				if( firstname.getText().toString().length() == 0 ){
					firstname.setError(  context.getString(R.string.secondNameRequire) );
					flag = false;
				}
				if( lastname.getText().toString().length() == 0 ){
					lastname.setError( context.getString(R.string.firstName) );
					flag = false;
				}
				EmailValidator ev = new EmailValidator();
				Log.e("EMAIL VALIDATE", ""+ev.validate(email.getText().toString()));
				if(!ev.validate(email.getText().toString())){
					email.setError( context.getString(R.string.emailRequire) );
					flag = false;
				}
				
				if( pwd.getText().toString().length() < 6 ){
					pwd.setError( context.getString(R.string.mdpRequire) );
					flag = false;
				}
				if( !pwd.getText().toString().equals(pwd2.getText().toString()) ){
					pwd.setError( context.getString(R.string.mdpError) );
					flag = false;
				}
				
				
				if(flag){
					mProgress.setMessage("Inscription & connexion ...");
			  		 mProgress.show();
			  		 
			  		 final String urlprofileGoogle=context.getResources().getString(R.string.liengoogle)+"s2/photos/profile/";
       				
					final User user = new User();
                	user.setUsername(firstname.getText().toString()+""+lastname.getText().toString());
  		        	user.setFirst_name(firstname.getText().toString());
  		        	user.setLast_name(lastname.getText().toString());
  		        	user.setEmail(email.getText().toString());
  		        	Currency currency = Currency.getInstance(Locale.getDefault());
  		        	user.setCurrency(currency.getCurrencyCode());
  		        	String str[]=email.getText().toString().split("@");
  		        	if(str[1].equals("gmail.com"))
  		        		user.setPicture(urlprofileGoogle+str[0]);
  		        	
  		        	new Thread() {
              			@Override
              			public void run() {
              		        try {
              		        	
              		        	// Create a new HttpClient and Post Header
              		            HttpClient httpclient = new DefaultHttpClient();
              		    	  final String urluser=context.getResources().getString(R.string.lien)+"api/user/new?json=";
              				
              		            HttpPost httppost = new HttpPost(urluser+URLEncoder.encode(user.toJSON(), "UTF-8"));

              			            try {
              	
              			                // Execute HTTP Post Request
              			                HttpResponse response = httpclient.execute(httppost);
              			                String content = EntityUtils.toString(response.getEntity());
              			                Log.e("HTTP", content);
              			                // Write to file
              			                writeFile("user.info", content);

              			            } catch (ClientProtocolException e) {
              			                // TODO Auto-generated catch block
              			            } catch (IOException e) {
              			                // TODO Auto-generated catch block
              			            }
              		        } catch (Exception ex) {
              		        	Log.e("FACEBOOK",ex.toString());
              		        }
              		        
              		        mHandler.sendEmptyMessage(0);
              			}
              		}.start();
				}
			}
		});
		

	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			
			if (msg.what == 0) {
				final Intent category = new Intent(context, CategoryChoiceActivity.class);
	            	context.startActivity(category);
			} 
		}
	};
	
	private void writeFile(String file, String text){
		FileOutputStream fos;
		try {
			fos = context.openFileOutput(file, Context.MODE_PRIVATE);
			fos.write(text.getBytes());
        	fos.close();
		} catch (FileNotFoundException e) {
			Toast.makeText(context, "ERROR: can't open file", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			Toast.makeText(context, "ERROR: can't write file", Toast.LENGTH_SHORT).show();
		}	
	}

}
